﻿XPhoto.Workbench = (function () {
    var canvas = null;

    var bufferCanvas = null;

    var zoomFactor = 1;

    var zoomStep = 0.1;

    var log = XPhoto.Logger.log;

    var roundFn = XPhoto.Util.round;

    return {
        init: function (ct) {
            canvas = $('<canvas></canvas>');
            canvas.appendTo(ct);
            canvas = canvas[0];
            canvas.width = $(window).width();
            canvas.height = $(window).height() - 200;

            bufferCanvas = document.createElement('canvas');
        },

        load: function (src, callback) {
            var img = new Image();
            var that = this;

            img.onload = function () {
                log(src + ' loaded...');
                bufferCanvas.width = this.width;
                bufferCanvas.height = this.height;
                bufferCanvas.getContext('2d').drawImage(this, 0, 0, this.width, this.height);

                //fit the image
                var widthRatio = canvas.width / this.width;
                var heightRatio = canvas.height / this.height;
                log([widthRatio, heightRatio]);

                zoomFactor = (widthRatio > heightRatio) ? heightRatio : widthRatio;
                that.drawImage();

                if (callback) {
                    callback();
                }
            };
            img.src = src;
        },

        zoomIn: function () {
            zoomFactor += zoomStep;
            this.drawImage();
        },

        zoomOut: function () {
            zoomFactor -= zoomStep;
            this.drawImage();
        },

        zoom: function (factor) {
            zoomFactor = factor;
            this.drawImage();
        },

        drawImage: function () {
            var imgWidth = roundFn(bufferCanvas.width * zoomFactor);
            var imgHeight = roundFn(bufferCanvas.height * zoomFactor);
            var offsetX = roundFn((canvas.width - imgWidth) / 2);
            var offsetY = roundFn((canvas.height - imgHeight) / 2);

            var ctx = canvas.getContext('2d');
            ctx.clearRect(0, 0, canvas.width, canvas.height);
            ctx.drawImage(bufferCanvas, 0, 0, bufferCanvas.width, bufferCanvas.height, offsetX, offsetY, imgWidth, imgHeight);
        },

        reset: function () { }
    };
})();